<!--职务管理 RoleManagement-->
<template>
  <div class='page_format'>
    <div class="my_Select">
      <el-form :inline="true" class="search-form">
        <el-form-item>
          <el-button class="bt-color-tjd" type="primary" v-if="is_show_button('button_role_add')" @click="saveDataForm">添加</el-button>
        </el-form-item>
        <el-form-item>
          职务状态：
          <el-select v-model="status" placeholder="全部" style="width: 110px;" size="small" clearable
                     @change="handleQuery">
            <el-option
                v-for="(item, index) in statusData"
                :key="index"
                :label="`${item.label}`"
                :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
          <el-form-item>
            <el-input style="width:150px;margin-right:8px" size="small" placeholder="职务名称"
                      v-model.number="queryValue"
                      clearable></el-input>
            <el-button size="small" @click="handleQuery" icon="el-icon-search" type="primary">查询</el-button>
          </el-form-item>
      </el-form>
    </div>
    <el-table :data="list" border style="width: 100%">
      <el-table-column type="index" :index="sort" label="序号" width="50"></el-table-column>
      <el-table-column prop="roleName" label="职务名称"></el-table-column>
      <el-table-column prop="userCount" label="职务人员">
        <template v-slot="scope">
          <div @click="handleUserDetailShow(scope.row)" style="color: #409eff;cursor: pointer;">{{ scope.row.userCount
            }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="职务描述"></el-table-column>
      <el-table-column label="启用"  align="center">
        <template v-slot="scope">
          <el-tag type="success" v-if="scope.row.status === '0'" size="small">是</el-tag>
          <el-tag type="danger" v-else size="small">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="最新操作时间"></el-table-column>
      <el-table-column label="操作" align="center">
        <template v-slot="scope">
          <div>
            <el-button v-if="is_show_button('button_role_setting_permissions')" @click="handleSetPermissions(scope.row)" type="text" size="small">
              设置权限
            </el-button>
          </div>
          <div>
            <el-button v-if="is_show_button('button_role_edit')" @click="handleClick(scope.row)" type="text" size="small">
              编辑
            </el-button>
          </div>
          <el-button v-if="is_show_button('button_role_delete')" @click="handleButtonClick(scope.row)" type="text" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="form.userId ?'修改':'添加'" :visible.sync="dialogFormVisible" center width="500px"
               @close="closeDialog">
      <el-form :model="form" :rules="rules" ref="dialogForm">
        <el-form-item label="职务名称：" :label-width="formLabelWidth" prop="roleName">
          <el-input v-model="form.roleName" autocomplete="off" placeholder="请填写职务名称" style="width: 100%;"></el-input>
        </el-form-item>
        <el-form-item label="职务描述：" :label-width="formLabelWidth" >
          <el-input v-model="form.remark" autocomplete="off" placeholder="输入职务描述" style="width: 100%;"></el-input>
        </el-form-item>
        <el-form-item label="是否启用：" :label-width="formLabelWidth">
          <el-switch
            v-model="form.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-value="0"
            inactive-value="1"
          ></el-switch>
        </el-form-item>
      </el-form>

      <!-- 底部按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog" :disabled="submitLoading">取 消</el-button>
        <el-button class="bt-color-tjd" v-if="is_show_button('button_role_edit')" type="primary"
                   @click="saveDataApi" :loading="submitLoading">确 定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="设置权限" :visible.sync="setPermissionsShow" center width="900px"
               @close="closeDialog">
      <div>
        <el-divider :style="{ 'font-size': '16px', 'margin-top': '20px', 'margin-bottom': '20px' }"
                    content-position="left" >职务信息</el-divider>
        <el-form :model="form" :label-width="formLabelWidth" size="mini" class="detail">
          <el-form-item label="职务名称：" :label-width="formLabelWidth" style="display: inline-block; width: 40%;">
            <span>{{ form.roleName }}</span>
          </el-form-item>
        </el-form>
      </div>
      <el-divider :style="{ 'font-size': '16px', 'margin-top': '20px', 'margin-bottom': '20px' }"
                  content-position="left" >权限设置</el-divider>
      <el-form :model="form" :rules="rules" ref="dialogForm">
        <el-tree
          ref="menuTree"
          :data="menuTreeData"
          show-checkbox
          node-key="menuId"
          :props="defaultProps"
          @check-change="handleCheckChange"
        >
        </el-tree>
      </el-form>

      <!-- 底部按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog" :disabled="submitLoading">取 消</el-button>
        <el-button @click="resetSelection">重置</el-button>
        <el-button class="bt-color-tjd" v-if="is_show_button('button_role_setting_permissions')" type="primary"
                   @click="saveSetPermissionsDataApi" :loading="submitLoading">确 定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="职务人员" :visible.sync="userDetailShow" center width="900px">
      <el-table :data="userForm.userInfoList" border style="width: 100%">
        <el-table-column type="index" fixed :index="sort" label="序号" width="60" align="center"></el-table-column>
        <el-table-column prop="nickName" label="姓名"></el-table-column>
        <el-table-column prop="phoneNumber" label="手机号"></el-table-column>
        <el-table-column prop="email" label="邮箱地址"></el-table-column>
        <el-table-column prop="roleName" label="职务名称"></el-table-column>
      </el-table>
    </el-dialog>
    <Toast :dialogVisible="dialogVisible" @isDelete="deleteDataApi"></Toast>
  </div>
</template>

<script>
import { post } from '@/api/my_axios'
import { changSort } from '@/utils/aqi'

export default {
  name: '',
  data () {
    return {
      userDetailShow: false, // 查看人员
      setPermissionsShow: false, // 权限按钮loading
      submitLoading: false, // 按钮loading
      dialogFormVisible: false,
      dialogVisible: false,
      dialogShowS: false,
      form: {
        roleId: '',
        roleName: '',
        roleKey: '',
        roleType: '',
        remark: '',
        status: '',
        menuIdList: []
      },
      userForm: {
        userInfoList: [], // 人员列表
        roleName: '',
        pageSize: 20,
        pageNum: 1,
        total: 0
      },
      list: [],
      menuData: [],
      infoForm: {},
      checkedMenuIds: [], // 已勾选的菜单ID
      menuTreeData: [], // 菜单树数据
      defaultProps: { // 默认属性配置
        children: 'children', // 子节点字段
        label: 'menuName', // 显示名称字段
        key: 'menuId' // 唯一标识字段
      },
      formLabelWidth: '140px',
      pageSize: 20,
      pageNum: 1,
      total: 0,
      id: '',
      queryValue: '',
      status: '',
      rules: {
        roleName: [{ required: true, message: '必填项不能为空！', trigger: 'change' }]
      },
      statusData: [
        { value: '0', label: '启用' },
        { value: '1', label: '未启用' }
      ]
    }
  },

  mounted () {
    this.getRoleManagement()
    this.getAllMenuList()
  },

  methods: {
    // 排序 （序号）
    sort (index) {
      return changSort(index, this.pageNum, this.pageSize)
    },

    // 查看人员
    async handleUserDetailShow (row) {
      this.userForm.userInfoList = []
      this.$store.dispatch('getUserManagement', {
        pageSize: this.userForm.pageSize,
        pageNum: this.userForm.pageNum,
        roleId: row.roleId
      }).then(res => {
        // this.userForm.userInfoList = res.data
        console.log('接口返回的数据:', row.roleName) // 检查数据
        this.userForm.userInfoList = res.data.map(user => ({
          ...user,
          roleName: row.roleName // 确保 roleName 存在
        }))
        console.log('最终 userInfoList:', this.userForm.userInfoList)
        this.userForm.total = res.total
        this.userDetailShow = true
      })
    },

    // 新增
    saveDataForm () {
      Object.keys(this.form).forEach(key => {
        this.form[key] = ''
      })
      this.dialogFormVisible = true
      this.form.status = '0'
      this.form.menuIdList = []
    },

    // 修改
    async handleClick (data) {
      await this.getRoleInfo(data.roleId)
      this.dialogFormVisible = true
      Object.keys(data).forEach(key => {
        this.form[key] = data[key]
      })
      this.form.menuIdList = this.infoForm.menuIdList
    },

    // 关闭dialog框
    closeDialog () {
      this.setPermissionsShow = false // 权限按钮loading
      this.dialogFormVisible = false
      this.submitLoading = false
      this.$refs.dialogForm.resetFields()
      Object.keys(this.form).forEach(key => {
        this.form[key] = ''
      })
      this.form.menuIdList = []
    },

    getRoleManagement () {
      this.list = []
      this.$store.dispatch('getRoleManagement', {
        pageSize: this.pageSize,
        pageNum: this.pageNum,
        notQueriedRoleId: 2,
        queryValue: this.queryValue,
        status: this.status
      }).then(res => {
        this.list = res.data
        this.total = res.total
      })
    },

    saveDataApi () {
      this.$refs.dialogForm.validate(valid => {
        if (!valid) return false
        this.submitLoading = true
        this.form.roleKey = this.form.roleName
        if (!this.form.roleId) {
          this.form.roleType = '01'
          post('/api/crm/sys/manage/crm/role/addRole', this.form).then(req => {
            if (req && req.code === 200) {
              this.$message({ message: '保存成功', type: 'success' })
            } else {
              this.$message({ message: '保存失败', type: 'error' })
            }
          }).finally(() => {
            this.closeDialog()
            this.getRoleManagement()
          })
        } else {
          post('/api/crm/sys/manage/crm/role/editRole', this.form).then(req => {
            if (req && req.code === 200) {
              this.$message({ message: '保存成功', type: 'success' })
            } else {
              this.$message({ message: '保存失败', type: 'error' })
            }
          }).finally(() => {
            this.closeDialog()
            this.getRoleManagement()
          })
        }
      })
    },

    deleteDataApi (type) {
      if (type === 'ok') {
        post('/api/crm/sys/manage/crm/role/removeRole', this.id
        ).then(req => {
          if (req && req.code === 200) {
            this.$message({ message: '删除成功', type: 'success' })
            this.getRoleManagement()
          }
        })
      }
      this.dialogVisible = false
    },

    // 保存权限操作
    async saveSetPermissionsDataApi () {
      this.submitLoading = true
      this.form.menuIdList = this.checkedMenuIds
      post('/api/crm/sys/manage/crm/role/editRole', this.form).then(req => {
        if (req && req.code === 200) {
          this.$message({ message: '保存成功', type: 'success' })
        } else {
          this.$message({ message: '保存失败', type: 'error' })
        }
      }).finally(() => {
        this.closeDialog()
        this.getUserManagement()
      })
    },

    // 设置权限
    async handleSetPermissions (data) {
      // 等待数据获取完成
      await this.getRoleInfo(data.roleId)
      this.setPermissionsShow = true
      Object.keys(data).forEach(key => {
        this.form[key] = data[key]
      })
      this.checkedMenuIds = this.infoForm.menuIdList
      this.menuTreeData = this.formatToTree(this.menuData)
      // 延迟设置默认勾选，确保 `menuTreeData` 已渲染
      this.$nextTick(() => {
        if (this.$refs.menuTree) {
          this.$refs.menuTree.setCheckedKeys(this.checkedMenuIds) // 默认勾选节点
        }
      })
    },

    // 格式化数据为树形结构
    formatToTree (data) {
      const map = {}
      const result = []
      data.forEach((item) => (map[item.menuId] = { ...item, children: [] }))
      data.forEach((item) => {
        if (item.parentId !== '-1') {
          // map[item.parentId]?.children.push(map[item.menuId])
          if (map[item.parentId] && map[item.parentId].children) {
            map[item.parentId].children.push(map[item.menuId])
          }
        } else {
          result.push(map[item.menuId])
        }
      })
      return result
    },

    // 勾选变化事件处理
    handleCheckChange (node, isChecked, childrenChecked) {
      this.checkedMenuIds = this.$refs.menuTree.getCheckedKeys()
    },

    // 重置勾选
    resetSelection () {
      this.$refs.menuTree.setCheckedKeys([])
      this.checkedMenuIds = []
    },

    async getRoleInfo (id) {
      this.infoForm = {}
      const res = await this.$store.dispatch('getRoleInfo', id)
      this.infoForm = res.data
    },

    // 根据全部菜单信息
    getAllMenuList (value) {
      this.$store.dispatch('getAllMenuList', value).then(res => {
        this.menuData = res.data
      })
    },

    handleQuery () {
      this.pageNum = 1
      this.getRoleManagement()
    },

    handleSizeChange (val) {
      this.pageSize = val
      this.getRoleManagement()
    },

    handleCurrentChange (val) {
      this.pageNum = val
      this.getRoleManagement()
    },

    handleButtonClick (data) {
      if (data.userCount > 0) {
        this.$message.error('职务有成员时无法删除！')
        return
      }
      this.id = data.roleId
      this.dialogVisible = true
    },

    is_show_button (name) {
      let show = false
      this.$store.state.module1.menu_list.forEach(v => {
        // eslint-disable-next-line eqeqeq
        if (v.path === name) {
          show = true
        }
      })
      return show
    }
  }
}
</script>

<style lang='scss'>
  .page_format {
    padding: 56px 20px 140px 20px;
  }
  .search-form{
    margin-top: 10px;
  }

  .icon-image {
    width: auto;
    height: auto;
    object-fit: cover;
  }
</style>
